<?php
/**
 * 兰心书院模块微站定义
 *
 * @author 
 * @url http://bbs.we7.cc/
 */
defined('IN_IA') or exit('Access Denied');
require_once IA_ROOT.'/addons/junsion_listenbook/func.php';
define('RES', '../addons/junsion_listenbook/public/');
define('OD_ROOT', IA_ROOT . '/addons/junsion_listenbook/cert/');
class Junsion_listenbookModuleSite extends WeModuleSite {
	public function wurl($name,$params = array()){
		return $this->createWebUrl($name,$params);
	}
	
	public function murl($name,$params = array()){
		return $this->createMobileUrl($name,$params);
	}
	
	public function doMobileSendMsg(){
		global $_W;
		if(date('H') == 3){
			//凌晨三点为重置消息推送状态时间
			update('mem_book',['msg_status'=>0]);
		}
		else{			
			$cfg = $this->module['config'];
			set_time_limit(0);
			$listen_log = getall('select id,bmid from ' .tb('listen_log'). " where 1 and to_days(from_unixtime(createtime)) = to_days(now())");
			$con = '';
			if(!empty($listen_log)){
				foreach ($listen_log as $k => $v){
					$bmids[] = $v['bmid'];
				}
				$con = " and id not in (".implode(',', $bmids).") ";
			}
			file_put_contents(IA_ROOT."/addons/junsion_listenbook/msg", date('Y-m-d H:i:s')." sql:".'select id,bid,mid,msg_status,starttime,remind,guide_weid from ' .tb('mem_book'). " where status = 0 and isfinish = 0 and msg_status<2 {$con}"."\n",FILE_APPEND);
			$mem_books = getall('select id,bid,mid,msg_status,starttime,remind,guide_weid from ' .tb('mem_book'). " where status = 0 and isfinish = 0 and msg_status<2 {$con}");
			if(!empty($mem_books)){
				$url = $_W['siteroot']."app".substr($this->createMobileUrl('index'),1);
				$time = date('H:i');
				$time = intval(str_replace(':', '', $time));
				$wids = '';
				foreach ($mem_books as $k => $v){
					$bids[] = $v['bid'];
					$mids[] = $v['mid'];
					if(!empty($wids)) $wids .= ',';
					$wids .= $v['guide_weid'];
				}
				$books = getall('select id,title,class_num,weids from ' .tb('book'). " where id in (".implode(',', $bids).")",'id');
				$wids .= $_W['uniacid'];
				foreach ($books as $k => $v){
					if(!empty($v['weids'])){
						if(!empty($wids)) $wids .= ',';
						$wids .= $v['weids'];
					}
				}
				$wids = str_replace(',,', ',', $wids);
				$wids = explode(',', $wids);
				$wids = array_unique($wids);
				$mems = getall('select id,nickname,openid from ' .tb('mem'). " where id in (".implode(',', $mids).")",'id');
				foreach ($mem_books as $k => $v){
					if($v['msg_status']>=2) continue;
					$class_time = strtotime('+ '.$books[$v['bid']]['class_num'].' days', $v['starttime']);
					if(date('Ymd',$class_time) < date('Ymd') || date('Ymd',$v['starttime']) > date('Ymd')) continue;
					$remind = unserialize($v['remind']);
					if($remind[0]['status']==1 || !isset($remind[0]['status'])){
						if(empty($remind[0]['time'])) $first_time = 700;
						else $first_time = intval(str_replace(':', '', $remind[0]['time']));
					}
					else $first_time = 2500;
					if($remind[1]['status']==1 || !isset($remind[1]['status'])){
						if(empty($remind[1]['time'])) $sec_time = 1900;
						else $sec_time = intval(str_replace(':', '', $remind[1]['time']));
					}
					else $first_time = 2500;
					if(($time>=$first_time && $v['msg_status']==0) || ($time>=$sec_time && $v['msg_status']==1)){
						$res = sendListenMsg($wids, $books[$v['bid']], $mems[$v['mid']], $cfg, $url);
						update('mem_book',['msg_status'=>$v['msg_status']+1],['id'=>$v['id']]);
					}
					else{
						continue;
					}
				}
			}
		}
	}
	
	public function getMem($shareid = 0){
		global $_W,$_GPC;
		WXLimit();
		load()->model('mc');
		$fans = $_W['fans'];
		if (empty($fans['nickname']) || empty($fans['avatar'])){
			$fans = mc_oauth_userinfo();
		}
		$cfg = $this->module['config'];
		if(empty($cfg)) MSG('无法访问');
		if(empty($fans['nickname'])) $fans['nickname'] = $fans['tag']['nickname'];
		//if(empty($fans['openid'])) $fans['openid'] = 'oZF9AtyjefFqbdxDnUMLboQb9Z20';//$fans['openid'] = $fans['tag']['openid'];
		if(empty($fans['avatar'])) $fans['avatar'] = $fans['tag']['avatar'];
		if(empty($fans['avatar'])) $fans['avatar'] = $fans['headimgurl'];
// 		if(empty($fans['unionid']))
		$mem = get('select * from ' .tb('mem'). " where uniacid = '{$_W['uniacid']}' and openid='{$fans['openid']}'");
// 		else 
// 			$mem = get('select * from ' .tb('mem'). " where unionid='{$fans['unionid']}'");
		$fans['avatar'] = str_replace('132132', '132', $fans['avatar']);
		
		if (!$shareid && $_GPC['shareid']) $shareid = $_GPC['shareid'];
		if(empty($mem)){
			$mem = array(
					'uniacid' => $_W['uniacid'],
					'openid' => $_W['openid'],
					'nickname' => $fans['nickname'],
					'avatar' => $fans['avatar'],
					'unionid' => $fans['unionid'],
					'agentid' => $shareid,
					'createtime' => time(),
			);
			insert('mem', $mem);
			$mem['id'] = pdo_insertid();
		}
		else{
			$updateData = [];
			if($mem['avatar']!=$fans['avatar']) $updateData['avatar'] = $fans['avatar'];
			if($mem['nickname']!=$fans['nickname']) $updateData['nickname'] = $fans['nickname'];
			if(empty($mem['unionid']) && $fans['unionid']) $updateData['unionid'] = $fans['unionid'];
			if(!empty($updateData)) update('mem', $updateData, array('id'=>$mem['id']));
		}
		$mem['avatar'] = str_replace('132132', '132', $mem['avatar']);
		return $mem;
	}
	
	public function getShare($mem='', $cfg='', $mbid = 0){
		global $_W,$_GPC;
		if(empty($cfg)) $cfg = $this->module['config'];
		$mbid = $mbid?$mbid:$_COOKIE['mem_book'];
		$arr = array('agreement','index','log','mcredit');
		$share = $cfg['share'];
		$url = $_W['siteroot']."app".substr($this->createMobileUrl('index'),1);
		if (!in_array($_GPC['do'], $arr) && $mbid){
			$share['title'] = $share['ctitle'];
			$share['des'] = $share['cdes'];
			$share['pic'] = $share['cpic'];
			$bid = col('select bid from '.tb('mem_book')." where id='{$mbid}'");
			$bookname = col('select title from '.tb('book')." where id='{$bid}'");
			$share['title'] = str_replace('#coursename#', $bookname, $share['title']);
			$share['des'] = str_replace('#coursename#', $bookname, $share['des']);
			$url .= "&sharebid=".$bid;
		}
		$share['title'] = str_replace('#nickname#', $mem['nickname'], $share['title']);
		$share['des'] = str_replace('#nickname#', $mem['nickname'], $share['des']);
		if(!empty($share['pic'])) $share['pic'] = toimage($share['pic']);
		if(!empty($mem)) $url .= '&shareid='.$mem['id'];
		$share['url'] = $url;
		return $share;
	}
	
	/* 获取章节目录信息 包括是否解锁，$mbook为会员书本，$cid章节id返回该章节是否解锁,$t时间 返回该时间的章节 */
	public function getTodayChapter($mbook,$cid,$t){
		
		$time = time();
		$day = ceil(($time - $mbook['starttime'])/86400);
		$day = max(1,$day);
		
		$dirs = getall('select * from '.tb('book_directory')." where bid='{$mbook['bid']}' order by sort desc, id asc");
		$chaps = getall('select * from '.tb('book_chapter')." where bid='{$mbook['bid']}' order by sort desc, id asc");
		
		$num = 0;
		$week = array('日','一','二','三','四','五','六');
		$lock = 1;
		foreach ($dirs as $dk => $d){
			$ck = 0;
			$d['lock'] = 1;
			$exam = get('select id from '.tb('book_question')." where did='{$d['id']}'");
			if (!empty($exam)){
				$chaps[] = array(
						'did' => $d['id'],
						'title' => '在线试题',
						'type' => 'question'
				);
			}
			foreach ($chaps as $c){
				if ($d['id']!=$c['did']) continue;
				if ($num==0){
					$ct = $mbook['starttime'];
				}else{
					$ct = strtotime('+ '.$num.' days', $mbook['starttime']);
				}
				if ($c['type']!='question'){
					$c['type'] = 'chap';
				}
				$num++;
				$ck++;
				if ($day == $num){
					$dir = $dk+1;
					$chap = $ck;
				}
				//如果已经开课并且天数大于等于章节就解锁
				if ($time>=$mbook['starttime'] && $day >= $num){
					$d['lock'] = $c['lock'] = 0;
					if ($cid && $cid==$c['id']) $lock = 0;
					$r = get("select id from ".tb('bremark')." where cid='{$c['id']}' or title='{$c['title']}'");
					if ($r) $d['opennum']++;
				}else{
					$c['lock'] = 1;
				}
				$c['week'] = '周'.$week[date('w',$ct)];
				$c['date'] = date('m/d',$ct);
				unset($c['detail']);
				$chapter[$ck] = $c;
				
				if($t && date('Ymd',$t) == date('Ymd',$ct)){
					$tchap = $c;
				}
			}
			$list[$dk+1] = array('dir'=>$d,'chap'=>$chapter);
			unset($chapter);
		}
		if ($day>=$num && empty($dir) && empty($chap)){
			$dir = $dk+1;
			$chap = $ck;
		}
		
		return array('list'=>$list,'dir'=>$dir,'chap'=>$chap,'day'=>$day,'lock'=>$lock,'tchap'=>$tchap,'last_time'=>$ct);
		
	}
	
	public function createLinkQr($mid, $url){
		global  $_W;
		/*生成二维码-----引入PHP QR库文件*/
		include_once IA_ROOT.'/addons/'.$this->modulename.'/phpqrcode.php';
		$path = '../addons/'.$this->modulename.'/qrcode/';
		if (!file_exists($path)){
			mkdir($path,0777);
		}
		$q = $path.'weid'.$mid.'.png';
		if(file_exists($q)) return $q;
		$errorCorrectionLevel = "L";
		$matrixPointSize = "4";
		QRcode::png($url, $q, $errorCorrectionLevel, $matrixPointSize);
		return $q;
	}
	
	function saveImage($url,$tag = '') {
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_CUSTOMREQUEST, 'GET' );
		if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')){
			curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
		}
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		ob_start ();
		curl_exec ( $ch );
		$return_content = ob_get_contents ();
		ob_end_clean ();
		$return_code = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
		$filename = IA_ROOT."/addons/junsion_listenbook/qrcode/{$tag}.jpg";
		$fp= @fopen($filename,"a"); //将文件绑定到流 
		fwrite($fp,$return_content); //写入文件
		return $filename;
	}
	
	public function wechatRefund($transid,$fee,$refund_fee){
		global $_W;
		$cfg = $this->module['config'];
		$url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
		$post = array(
				'appid'=>$_W['uniaccount']['key'],
				'transaction_id'=>$transid,
				'nonce_str'=>random(8),
				'mch_id'=>$cfg['mchid'],
				'total_fee' => $fee * 100,
				'refund_fee' => $refund_fee * 100,
				'op_user_id' => $cfg['mchid'],
				'out_refund_no' =>random(32),
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$cfg['APPKEY']}";
		$sign = md5($string);
		$post['sign'] = strtoupper($sign);
		$extras = array();
		$extras['CURLOPT_CAINFO'] = OD_ROOT .md5("root{$_W['uniacid']}ca").".pem";
		$extras['CURLOPT_SSLCERT'] = OD_ROOT .md5("apiclient_{$_W['uniacid']}cert").".pem";
		$extras['CURLOPT_SSLKEY'] = OD_ROOT .md5("apiclient_{$_W['uniacid']}key").".pem";
		load()->func('communication');
		$resp = ihttp_request($url, $this->ToXml($post), $extras);
		libxml_disable_entity_loader(true);
		$resp = json_decode(json_encode(simplexml_load_string($resp['content'], 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		file_put_contents(IA_ROOT."/addons/junsion_listenbook/refund", date('Y-m-d H:i:s')."：  res:".json_encode($resp)."\n",FILE_APPEND);
		if ($resp['result_code'] != 'SUCCESS' || $resp['return_code'] != 'SUCCESS') {
			return array('errcode'=>1,'errmsg'=>json_encode($resp));
		}
		return array('errcode'=>0,'refund_id'=>$resp['refund_id'],'refund_fee'=>$resp['refund_fee']/100);
		
	}
	
	public function sendRedPacket($params){
		global $_W;
		$uniacid = $_W['uniacid'];
		if ($params['uniacid']) $uniacid = $params['uniacid'];
		$openid = $params['openid'];
		$money = floatval($params['price']);
		load()->func('communication');
		$cfg = $params['cfg']?$params['cfg']:$this->module['config'];
	
		$pars = array();
		$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';
		$pars['spbill_create_ip'] = trim($cfg['ip']);
		$pars['mch_appid'] = trim($_W['uniaccount']['key']);
		$pars['mchid'] = trim($cfg['mchid']);
		$pars['nonce_str'] = random(32);
		$pars['partner_trade_no'] = random(28);
		$pars['openid'] = $openid;
		$pars['check_name'] = 'NO_CHECK';
		$pars['amount'] = intval($money * 100);
		$pars['desc'] = "佣金提现";
	
		ksort($pars, SORT_STRING);
		$string1 = '';
		foreach($pars as $k => $v) {
			$string1 .= "{$k}={$v}&";
		}
		$string1 .= "key={$cfg['APPKEY']}";
		$pars['sign'] = strtoupper(md5($string1));
		$xml = array2xml($pars);
		$extras = array();
		$extras['CURLOPT_SSLCERT'] = OD_ROOT .md5("apiclient_{$uniacid}cert").".pem";
		$extras['CURLOPT_SSLKEY'] = OD_ROOT .md5("apiclient_{$uniacid}key").".pem";
		$resp = ihttp_request($url, $xml, $extras);
		if(is_error($resp)) {
			return array('code'=>-1,'msg'=>$resp['message']);
		} else {
			$xml = '<?xml version="1.0" encoding="utf-8"?>' . $resp['content'];
			$dom = new DOMDocument();
			if($dom->loadXML($xml)) {
				$xpath = new DOMXPath($dom);
				$send_listid = $xpath->evaluate('string(//xml/payment_no)');
				$code = $xpath->evaluate('string(//xml/return_code)');
				$ret = $xpath->evaluate('string(//xml/result_code)');
				if(strtolower($code) == 'success' && strtolower($ret) == 'success') {
					return array('code'=>1,'msg'=>$send_listid);
				} else {
					file_put_contents(IA_ROOT."/addons/junsion_listenbook/withfail", "\n".$procResult."\n".json_encode($pars),FILE_APPEND);
					$procResult = $xpath->evaluate('string(//xml/err_code_des)');
					$return = array('code'=>-1,'msg'=>$procResult);
					$code = $xpath->evaluate('string(//xml/err_code)');
					if (strtoupper($code) == 'OPENID_ERROR') $return['code'] = -2;
					elseif (strtoupper($code) == 'V2_ACCOUNT_SIMPLE_BAN') $return['code'] = -3;
					return $return;
				}
			} else {
				return array('code'=>-1,'msg'=>'error response');
			}
		}
	}

	public function culCommission($book,$mid, $money, $cfg = ''){
		global $_W;
		if ($book['commission']){
			$coms = unserialize($book['commission']);
			if ($coms['status'] == 2) return 0;
		}
		$mem = get('select id,agentid from ' .tb('mem'). " where id='{$mid}'");
		if(empty($mem['agentid'])) return 0;
		$agent = get('select id,agentid from ' .tb('mem'). " where id='{$mem['agentid']}'");
		if(empty($agent)) return 0;
		if(empty($cfg)) $cfg = $this->module['config']['commission'];
		if(empty($cfg['status'])) return 0;
		if ($coms['status'] == 1){
			$cfg['rate'] = $coms['rate'];
			$cfg['rate2'] = $coms['rate2'];
			$cfg['rate3'] = $coms['rate3'];
		}
		if($cfg['status']>=1){
			if($cfg['rate']>0){
				$credit = $money * $cfg['rate'] / 100;
				$credit = intval($credit * 100) / 100;
			}
			if($credit>0) {
				updateMemCredit(array('mid'=>$agent['id'], 'aid'=>$mid, 'credit'=> $credit, 'remark'=>'一级佣金'));
			}
			if($cfg['status']>=2){
				if(empty($agent['agentid'])) return 0;
				$agent2 = get('select id,agentid from ' .tb('mem'). " where id='{$agent['agentid']}'");
				if($cfg['rate2']>0){
					$credit2 = $money * $cfg['rate2'] / 100;
					$credit2 = intval($credit2 * 100) / 100;
				}
				if($credit2>0) {
					updateMemCredit(array('mid'=>$agent2['id'], 'aid'=>$mid, 'credit'=> $credit2, 'remark'=>'二级佣金'));
				}
				if($cfg['status']>=3){
					if(empty($agent2['agentid'])) return 0;
					$agent3 = get('select id from ' .tb('mem'). " where id='{$agent2['agentid']}'");
					if($cfg['rate3']>0){
						$credit3 = $money * $cfg['rate3'] / 100;
						$credit3 = intval($credit3 * 100) / 100;
					}
					if($credit3>0) {
						updateMemCredit(array('mid'=>$agent3['id'], 'aid'=>$mid, 'credit'=> $credit3, 'remark'=>'三级佣金'));
					}
				}
			}
		}
		return 1;
	}
	
	public function payResult($params){
		global $_W, $_GPC;
		if($params['table'] == 'recharge'){
			$order = get('select * from '.tb('recharge')." where ordersn='{$params['tid']}'");
			if(empty($order) || $order['status'] == 1){
				return "";
			}
			if ($params['from'] == 'notify') {
				if ($params['type'] == 'credit'){
					$res['code']=1;
					$res['fee'] = $params['fee'];
				}else{
					$res = $this->checkWechatTran($_W['uniacid'], $params['tag']['transaction_id']);
				}
				if ($res['code']==1 && $res['fee'] == $order['price']){
					update('recharge',array('status'=>1,'transid'=>$params['tag']['transaction_id']),array('id'=>$order['id']));
					updateMemScore(['mid'=>$order['mid'], 'score'=>$order['score'], 'remark'=>'充值成长星']);
				}
			}
		}
		else{
			$order = get('select * from '.tb('order')." where ordersn='{$params['tid']}'");
			if(empty($order) || $order['status'] == 1){
				return "";
			}
			if ($params['from'] == 'notify') {
				if ($params['type'] == 'credit'){
					$res['code']=1;
					$res['fee'] = $params['fee'];
				}else{
					$res = $this->checkWechatTran($_W['uniacid'], $params['tag']['transaction_id']);
				}
					
				if ($res['code']==1 && $res['fee'] == $order['price']){
					$book = get('select id,uniacid,title,start_day,weids,commission from '.tb('book')." where id='{$order['bid']}'");
					update('order',array('status'=>1,'transid'=>$params['tag']['transaction_id']),array('id'=>$order['id']));
					$this->culCommission($book,$order['mid'], $order['price']);
					if($book['start_day']==-1) $startime = strtotime(date('Y-m-d'));
					else $startime = getNextWeekDate($book['start_day']); 
					if(empty($book['weids'])){
						$guide_weid = $book['uniacid'];
					}
					else{
						$wids = explode(",", $book['weids']);
						shuffle($wids);
						$guide_weid = $wids[0];
					}
					$data = array(
							'uniacid' => $_W['uniacid'],
							'mid' => $order['mid'],
							'bid' => $order['bid'],
							'oid' => $order['id'],
							'price' => $order['price'],
							'uname' => $order['uname'],
							'mobile' => $order['mobile'],
							'studentid' => date('Ymd').random(4,1),
							'createtime' => time(),
							'starttime' => $startime,
							'guide_weid' => $guide_weid
					);
					insert('mem_book',$data);
					sendPaySucMsg($order, $book);
				}
			}
		}
	}
	
	public function unifiedOrder($remark,$fee,$orderid=0,$table='order'){
		global $_W;
		$url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		$random = random(8);
		load()->model('payment');
		$options = $this->module['config'];
		$post = array(
				'appid'=>$_W['account']['key'],
				'mch_id'=>$options['mchid'],
				'nonce_str'=>$random,
				'body'=>$remark,
				'out_trade_no'=>$orderid,
				'total_fee'=>$fee*100,
				'spbill_create_ip'=>CLIENT_IP,
				'notify_url'=>$_W['siteroot'].'/addons/'.$this->modulename.'/notify.php',
				'trade_type'=>'JSAPI',
				'openid'=>$_W['openid'],
				'attach'=>$_W['uniacid'].':'.$table,
				'limit_pay'=>'no_credit',
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$options['APPKEY']}";
		$sign = md5($string);
		$post['sign'] = strtoupper($sign);
		$resp = $this->postXmlCurl($this->ToXml($post), $url);
		libxml_disable_entity_loader(true);
		$resp = json_decode(json_encode(simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		if ($resp['result_code'] != 'SUCCESS') {
			return array('errcode'=>1,'errmsg'=>json_encode($resp));
		}else{
			return array('errcode'=>0,'prepay_id'=>$resp['prepay_id'],'code_url'=>$resp['code_url']);
		}
	}
	
	/**
	 * 支付js pai 参数
	 * @param unknown $prepay_id
	 * @return multitype:string NULL unknown
	 */
	public function getWxPayJsParams($prepay_id){
		global $_W;
		load()->model('payment');
		$options = $this->module['config'];
		$random = random(8);
		$post = array(
				'appId'=>$_W['account']['key'],
				'timeStamp'=>time().'',
				'nonceStr'=>$random,
				'package'=>"prepay_id=".$prepay_id,
				'signType'=>'MD5',
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$options['APPKEY']}";
		$sign = md5($string);
		$post['paySign'] = strtoupper($sign);
		return $post;
	}
	
	private function ToUrlParams($post)
	{
		$buff = "";
		foreach ($post as $k => $v)
		{
			if($k != "sign" && $v != "" && !is_array($v)){
				$buff .= $k . "=" . $v . "&";
			}
		}
	
		$buff = trim($buff, "&");
		return $buff;
	}
	
	private function ToXml($post)
	{
		$xml = "<xml>";
		foreach ($post as $key=>$val)
		{
			if (is_numeric($val)){
				$xml.="<".$key.">".$val."</".$key.">";
			}else{
				$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
			}
		}
		$xml.="</xml>";
		return $xml;
	}
	
	private function checkWechatTran($uniacid,$transid){
		$_W['account'] = uni_fetch($uniacid);
		$wechat = $this->module['config'];
		$url = "https://api.mch.weixin.qq.com/pay/orderquery";
		$random = random(8);
		$post = array(
				'appid'=>$_W['account']['key'],
				'transaction_id'=>$transid,
				'nonce_str'=>$random,
				'mch_id'=>$wechat['mchid'],
		);
		ksort($post);
		$string = $this->ToUrlParams($post);
		$string .= "&key={$wechat['APPKEY']}";
		$sign = md5($string);
		$post['sign'] = strtoupper($sign);
		$resp = $this->postXmlCurl($this->ToXml($post), $url);
		libxml_disable_entity_loader(true);
		$resp = json_decode(json_encode(simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
		if ($resp['result_code'] != 'SUCCESS' || $resp['return_code'] != 'SUCCESS') {
			file_put_contents(IA_ROOT."/addons/junsion_listenbook/res", json_encode($resp));
			exit('fail');
		}
		if ($resp['trade_state'] == 'SUCCESS') return array('code'=>1,'fee'=>$resp['total_fee']/100);
	}
	
	private function postXmlCurl($xml, $url, $useCert = false, $second = 30){
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, $second);
	
		curl_setopt($ch,CURLOPT_URL, $url);
		curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);//严格校验
		//设置header
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		//要求结果为字符串且输出到屏幕上
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	
		if($useCert == true){
			//设置证书
			//使用证书：cert 与 key 分别属于两个.pem文件
			curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
			curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
			curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
		}
		//post提交方式
		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
		//运行curl
		$data = curl_exec($ch);
		//返回结果
		if($data){
			curl_close($ch);
			return $data;
		}
	}
	
	function getQR($params){
		global $_W;
		$wid = $params['wid'];
		$url = $params['url'];
		$mid = $params['mid'];
		if(empty($wid)) $wid = $_W['uniacid'];
		$name = $this->modulename.$_W['uniacid'];
		$str = "_sub";
		if ($mid){
			$str = '_agentid_'.$mid;
		}
		$qr = pdo_fetch('select * from '.tablename('qrcode')." where uniacid='{$wid}' and `name`='{$name}' and `keyword`='".$this->modulename."'");
		if (!empty($qr)){
			if ($url) return $qr['url'];
			return $img = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($qr['ticket']);
		}
		$barcode['action_info']['scene']['scene_str'] = $this->modulename.$str;
		load()->model('account');
		$acid = pdo_fetchcolumn('select acid from '.tablename('account')." where uniacid={$wid}");
		$uniacccount = WeAccount::create($acid);
		
		$time = 0;
		$barcode['action_name'] = 'QR_LIMIT_STR_SCENE';
		$res = $uniacccount->barCodeCreateFixed($barcode);
		$qrcode = array(
				'uniacid'=>$wid,
				'acid'=>$wid,
				'name'=>$name,
				'keyword'=>$this->modulename,
				'ticket'=>$res['ticket'],
				'expire'=>$time,
				'createtime'=>time(),
				'status'=>1,
				'url'=>$res['url']
		);
		$qrcode['scene_str'] = $barcode['action_info']['scene']['scene_str'];
		$qrcode['model'] = 2;
		$qrcode['type'] = 'scene';
		//将二维码存于微擎官方二维码表
		pdo_insert('qrcode',$qrcode);
	
		$r = pdo_fetch('select id from '.tablename("rule")." where module='".$this->modulename."' and uniacid='{$wid}'");
		if (empty($r)){
			pdo_insert('rule',array('uniacid'=>$wid,'name'=>$this->modulename,'module'=>$this->modulename,'displayorder'=>254,'status'=>1));
			$id = pdo_insertid();
			//插入关注关键字
			$rule = array(
				'uniacid' => $wid,
				'module' => $this->modulename,
				'status' => 1,
				'displayorder' => 254,
				'rid'=>$id,
				'type'=>1,
				'content'=>$this->modulename,
			);
			pdo_insert('rule_keyword',$rule);
		}else{
			$rk = pdo_fetch('select id from '.tablename("rule_keyword")." where rid='{$r['id']}' and content='".$this->modulename."'");
			if (empty($rk)){
				//插入关注关键字
				$rule = array(
					'uniacid' => $wid,
					'module' => $this->modulename,
					'status' => 1,
					'displayorder' => 254,
					'rid'=>$r['id'],
					'type'=>1,
					'content'=>$this->modulename,
				);
				pdo_insert('rule_keyword',$rule);
			}
		}
		if ($url) return $res['url'];
		return $img = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . urlencode($res['ticket']);
	}
	
	public function getLevelAgent($mid,$level=0){
		global $_W;
		if(empty($mid)) return 0;
		$con = '';
		if(!empty($mid)) $con .= " and agentid = '{$mid}' ";
		$level1 = getall('select id from ' .tb('mem'). " where uniacid = '{$_W['uniacid']}' and (avatar != '' or nickname != '') {$con}");
		if($level>=0){
			if(!empty($level1)){
				foreach ($level1 as $k => $v){
					$levelAgentids[] = $v['id'];
				}
				if($level==0) return $levelAgentids;
				if($level>=1 && !empty($levelAgentids)){
					$level2 = getall('select id from ' .tb('mem'). " where uniacid = '{$_W['uniacid']}' and (avatar != '' or nickname != '') and agentid in (".implode(',', $levelAgentids).")");
					if(!empty($level2)){
						foreach ($level2 as $k => $v){
							$levelAgentids2[] = $v['id'];
						}
						return $levelAgentids2;
					}
				}
			}
		}
		return 0;
	}
	
}
